package com.sentinel.client.conf;


import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.cloud.utils.base.DataResult;
import com.cloud.utils.common.ResponseFormatter;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;



/**
 * 自定义sentinel异常返回信息
 * @author 86173
 */
@Configuration
public class ExceptionHandlerPage implements BlockExceptionHandler {

    private static Logger log = LoggerFactory.getLogger(ExceptionHandlerPage.class);

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse res, BlockException ex) throws Exception {
        System.err.println("===========进入sentinel异常=-=-=-=-=-=-=-=-=-=-=-=-");

        if(ex instanceof FlowException) {
            ResponseFormatter.initResponse(res, DataResult.buildFail(100,"限流"));
        }else if(ex instanceof DegradeException) {
            ResponseFormatter.initResponse(res, DataResult.buildFail(100,"降级"));
        }else if(ex instanceof ParamFlowException) {
            ResponseFormatter.initResponse(res, DataResult.buildFail(100,"热点参数降级"));
        }else if(ex instanceof SystemBlockException ) {
            ResponseFormatter.initResponse(res, DataResult.buildFail(100,"系统规则限流"));
        }else if(ex instanceof AuthorityException) {
            ResponseFormatter.initResponse(res, DataResult.buildFail(100,"授权不通过"));
        }else {
            ResponseFormatter.initResponse(res, DataResult.buildFail(201, ex.getMessage()));
        }
    }
}